package com.cos.shop.service.impl;

import com.cos.shop.common.ResponseResult;
import com.cos.shop.dao.CartDao;
import com.cos.shop.dao.ProductDao;
import com.cos.shop.dao.impl.CartDaoImpl;
import com.cos.shop.dao.impl.ProductDaoImpl;
import com.cos.shop.entity.Cart;
import com.cos.shop.entity.Product;
import com.cos.shop.entity.vo.CartVo;
import com.cos.shop.service.CartServices;

import java.sql.SQLException;
import java.util.List;

/**
 * Copyright (C),2021-2022,亚瑟王
 * FileName: CartServicesImpl
 * Author: saber
 * Date:2022/9/19 13:35
 */
public class CartServicesImpl implements CartServices {
    private CartDao cd = new CartDaoImpl();
    private ProductDao pd = new ProductDaoImpl();

    @Override
    public ResponseResult addCart(int uid, int pid) {
        try {
            if (pid>0){
                Product product = pd.getProductByPid(pid);
                Cart c = cd.findByUidAndPid(uid, pid);
                if (c==null) {
                    c = new Cart(uid,pid,product.getPprice(),1);
                    cd.addCart(c);
                }else {
                    c.setCnum(c.getCnum()+1);
                    c.setCcount(c.getCnum()*product.getPprice());
                }
                return ResponseResult.createSuccess("购物车添加成功");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return ResponseResult.createFail("购物车添加失败,请稍后再试");
    }

    @Override
    public ResponseResult getCartList(int uid) {
        try {
            List<CartVo> cartVoList = cd.getCartAll(uid);
            return ResponseResult.createSuccess(cartVoList);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ResponseResult.createFail("购物车暂无数据");
    }

    @Override
    public ResponseResult updateCartNum(int uid, int pid, int num) {
        try {
            int i =0;
            if (num==0) {
                i =cd.deleteCart(uid, pid);
            }else {

                Cart cart= cd.findByUidAndPid(uid, pid);

                Product p = pd.getProductByPid(pid);

                cart.setCnum(cart.getCnum()+num);

                cart.setCcount(cart.getCnum()*p.getPprice());

                i = cd.updateCart(cart);
            }
            return ResponseResult.createSuccess("购物车修改成功");
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return ResponseResult.createFail("购物车修改失败");
    }

    @Override
    public ResponseResult clearCart(int uid, int pid) {
        try {
            int i = 0;
            if (pid == 0) {
                i = cd.deleteCart(uid);
            } else {
                i = cd.deleteCart(uid, pid);
            }
            if (i > 0) {
                return ResponseResult.createSuccess("购物车清空成功");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ResponseResult.createFail("购物车清空失败");
    }
}
